{% extends "base.html" %}
{% load static %}

{% block title %}OPC UA订阅列表{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>OPC UA订阅列表</h2>
        <a href="{% url 'opcua_subscription_add' %}" class="btn btn-primary">
            <i class="bi bi-plus-circle"></i> 添加订阅
        </a>
    </div>

    <div class="card mb-4">
        <div class="card-body">
            <form method="get" class="row g-3">
                {{ filter.form.as_p }}
                <div class="col-12">
                    <button type="submit" class="btn btn-secondary">
                        <i class="bi bi-search"></i> 筛选
                    </button>
                    <a href="{% url 'opcua_subscription_list' %}" class="btn btn-outline-secondary">
                        <i class="bi bi-x-circle"></i> 清除筛选
                    </a>
                </div>
            </form>
        </div>
    </div>

    <div class="table-responsive">
        {% csrf_token %}
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>数据源</th>
                    <th>节点名称</th>
                    <th>节点ID</th>
                    <th>报警条件</th>
                    <th>阈值</th>
                    <th>单位</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for subscription in subscriptions %}
                <tr>
                    <td>{{ subscription.data_source.name }}</td>
                    <td>{{ subscription.name }}</td>
                    <td>{{ subscription.node_id }}</td>
                    <td>{{ subscription.get_condition_display }}</td>
                    <td>
                        {% if subscription.condition == 'range' %}
                            {{ subscription.threshold_value }} - {{ subscription.threshold_max }}
                        {% else %}
                            {{ subscription.threshold_value }}
                        {% endif %}
                    </td>
                    <td>{{ subscription.unit }}</td>
                    <td>
                        {% if subscription.is_active %}
                            <span class="badge bg-success">启用</span>
                        {% else %}
                            <span class="badge bg-secondary">禁用</span>
                        {% endif %}
                    </td>
                    <td>
                        <div class="btn-group" role="group">
                            <a href="{% url 'opcua_subscription_edit' subscription.id %}" 
                               class="btn btn-sm btn-outline-primary"
                               title="编辑">
                                <i class="bi bi-pencil"></i>
                            </a>
                            <a href="{% url 'opcua_subscription_delete' subscription.id %}" 
                               class="btn btn-sm btn-outline-danger"
                               title="删除">
                                <i class="bi bi-trash"></i>
                            </a>
                            <button type="button" 
                                    class="btn btn-sm {% if subscription.is_active %}btn-outline-warning{% else %}btn-outline-success{% endif %} toggle-status"
                                    data-subscription-id="{{ subscription.id }}"
                                    title="{% if subscription.is_active %}禁用{% else %}启用{% endif %}">
                                <i class="bi {% if subscription.is_active %}bi-pause-fill{% else %}bi-play-fill{% endif %}"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                {% empty %}
                <tr>
                    <td colspan="7" class="text-center">暂无订阅数据</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    {% if is_paginated %}
    <nav aria-label="分页">
        <ul class="pagination justify-content-center">
            {% if page_obj.has_previous %}
            <li class="page-item">
                <a class="page-link" href="?page=1">&laquo; 首页</a>
            </li>
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.previous_page_number }}">上一页</a>
            </li>
            {% endif %}

            <li class="page-item active">
                <span class="page-link">
                    第 {{ page_obj.number }} 页，共 {{ page_obj.paginator.num_pages }} 页
                </span>
            </li>

            {% if page_obj.has_next %}
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.next_page_number }}">下一页</a>
            </li>
            <li class="page-item">
                <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}">末页 &raquo;</a>
            </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 切换状态按钮点击事件
    document.querySelectorAll('.toggle-status').forEach(button => {
        button.addEventListener('click', function() {
            const subscriptionId = this.dataset.subscriptionId;
            const currentStatus = this.title === '禁用';  // 当前是启用状态
            
            // 禁用按钮，防止重复点击
            this.disabled = true;
            
            fetch(`/subscriptions/opcua/${subscriptionId}/toggle/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新按钮状态
                    this.title = currentStatus ? '启用' : '禁用';
                    this.classList.toggle('btn-outline-warning');
                    this.classList.toggle('btn-outline-success');
                    this.querySelector('i').classList.toggle('bi-pause-fill');
                    this.querySelector('i').classList.toggle('bi-play-fill');
                    
                    // 更新状态标签
                    const statusBadge = this.closest('tr').querySelector('.badge');
                    if (statusBadge) {
                        statusBadge.textContent = currentStatus ? '禁用' : '启用';
                        statusBadge.classList.toggle('bg-success');
                        statusBadge.classList.toggle('bg-secondary');
                    }
                    
                    // 显示成功消息
                    const message = `订阅已${data.status}`;
                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-success alert-dismissible fade show';
                    alertDiv.innerHTML = `
                        ${message}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    `;
                    document.querySelector('.container').insertBefore(alertDiv, document.querySelector('.container').firstChild);
                    
                    // 3秒后自动关闭提示
                    setTimeout(() => {
                        alertDiv.remove();
                    }, 3000);
                } else {
                    alert('操作失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请重试');
            })
            .finally(() => {
                // 重新启用按钮
                this.disabled = false;
            });
        });
    });
});
</script>
{% endblock %} 